<?php

class AgentModel extends Model {
	
	public function getAgent($uid){
		$map['id']		 = $uid;
		$map['role']	 = 'agent';
		//是否激活，是否可用。在上一层判断个状态提示用户。
		$user = model('User')->where($map)->find();
		//dump($user);
		if(!$user){
			return false;
		}else if($user['role']=='agent'){
			unset($map);
			$map['user_id']=$uid;
			//$map['enable']='Y';
			$agent = $this->where($map)->find();
			if(!empty($agent))$user['agent']=$agent;
			return $user;
		}
		return false;
	}
	
	
	public function selectAgents($limit=5){
		$agents = $this->where(array('enable'=>'Y','is_delete'=>'N'))->order('ctime desc')->limit($limit)->findAll();
		return $agents;
	}
	
	
	function deleteRebate($order_id,$reason='订单被撤销！',$admin_id=''){
		if(!empty($admin_id))$data['modify_admin_id']=$admin_id;
		$data['reason']=$reason;
		$data['enable']='N';
		$data['mtime']=time();
		if(is_array($order_id))$map['order_id']=array('in',$order_id);
		else $map['order_id']=$order_id;
		$this->where(array('order_id'=>$order_id))->save($data);
	}
	
	function addRebate($agent_id,$order_id,$total_fee,$paid_money,$rebate_value,$rebate_model){
		//echo "<br>".$agent_id."-".$order_id."-".$total_fee."-".$paid_money."-".$rebate_value."-".$rebate_model;
		$user = $this->getAgent($agent_id);
		if(!$user)return;
		if($user['enable']!='Y'||empty($user['agent'])||$user['agent']['enable']!='Y'){
			return;
		}
		
		//计算返利金额
		$rebate_money = countRebateValue($total_fee,$paid_money,$rebate_value,$rebate_model);
		//echo $rebate_money;
		$data['order_id']=$order_id;
		$data['user_id']=$agent_id;
		$data['amount']=$total_fee;
		$data['pay_money']=$paid_money;
		$data['rebate_money']=$rebate_money;
		$data['rebate_value']=$rebate_value;
		$data['rebate_model']=$rebate_model;
		$data['ctime']=time();
		$data['enable']='Y';
		//dump($data);
		M("AgentRebate")->add($data);
	}
	
	
	/**
	 * 搜索用户返利数据，搜索当前月份的内的返利
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $month_		月份格式 '2011-12-01'
	 * @param unknown_type $type_		搜索类型  all-全部  Y-有效的  N-无效的
	 */
	function searchRebate($user_id,$month_,$type_='all'){
		$where['user_id'] = $user_id;
		$endtime = strtotime("+1months",strtotime($month_));  
		$starttime = strtotime($month_); 
		$where['ctime'] = array('EXP','>='.$starttime.' and `ctime`<'.$endtime);
		
		if(in_array($type_,array('Y','N'))){
			$where['enable'] = $type_;
		}
		
		$order='ctime desc';
		$pagedata = M("AgentRebate")->kPageQuery($where,$order,20);
		//echo $mobile.'--'.$orderdao->getLastSql();
		return $pagedata;
	}
	
	/**
	 * 计算用户有效订单数
	 * @param unknown_type $user_id
	 */
	function countAgentRebate($user_id){
		$where['user_id'] = $user_id;
		$where['enable'] = 'Y';
		
		$no = M("AgentRebate")->where($where)->count();
		//echo $mobile.'--'.$orderdao->getLastSql();
		return $no;
	}
}
?>